/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

package util

import (
	"bytes"
	"math/rand"
	"time"

	"github.com/fogleman/gg"
)

// GetRandStr  获取验证码内容，n表示验证码长度
func GetRandStr(n int) (randStr string) {
	chars := "ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789"
	charsLen := len(chars)
	if n > 10 {
		n = 10
	}
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < n; i++ {
		randIndex := rand.Intn(charsLen)
		randStr += chars[randIndex : randIndex+1]
	}
	return randStr
}

// ImgText width，height表示验证码的宽和高
func ImgText(width, height int, text string) (b []byte) {
	textLen := len(text)
	context := gg.NewContext(width, height)
	context.SetRGBA255(14, 22, 42, 255)
	context.Clear()

	fontSize := float64(height / 2)

	for i := 0; i < len(text); i++ {
		context.SetRGBA255(145, 152, 164, 255)
		x := float64(width/textLen*i) + fontSize*0.6
		y := float64(height / 2)
		writeTextToImg(context, text[i:i+1], float64(x), y)
	}
	buffer := bytes.NewBuffer(nil)
	context.EncodePNG(buffer)
	b = buffer.Bytes()
	return
}

func writeTextToImg(context *gg.Context, text string, x, y float64) {
	xfload := 5 - rand.Float64()*10 + x
	yfload := 5 - rand.Float64()*10 + y

	radians := 40 - rand.Float64()*80
	context.RotateAbout(-1*gg.Radians(radians), x, y)
	context.RotateAbout(gg.Radians(radians), x, y)
	context.DrawStringAnchored(text, xfload, yfload, 0.2, 0.5)
	context.Stroke()
}
